package controller;

import java.awt.event.*;
import javax.swing.JOptionPane;
import model.GameClient;
import javax.swing.*;
import java.net.*;
import java.awt.*;
import java.io.*;

public class ConnectListener implements ActionListener
{
	private GameClient gameClient;

	public ConnectListener(GameClient gameClient)
	{
		super();
		this.gameClient = gameClient;
	}

	public void actionPerformed(ActionEvent e) 
	{
		try 
		{
			// Check if already connected
			if(gameClient.checkConnected() == false){
				/* 	Create a socket to connect to the server
				 * 	Errors will be caught at the GameClient level 
				 */
				gameClient.createSocket();

				/* 	Create an Input Stream to receive data from the server from the socket created above
				 * 
				 * 	DEBUG COMMENTS: An NullPointerException will occur below and an exception will be
				 * 	 thrown when the Socket above failed to be created
				 */
				gameClient.setInputFromServer(new BufferedReader(new InputStreamReader(gameClient.getSocket().getInputStream())));

				// Create an Output Stream to send data to the server
				gameClient.setOutputToServer(new PrintWriter(gameClient.getSocket().getOutputStream()));

				// Set the gameClient status as Connected
				gameClient.setConnected();
			} else {
				JOptionPane.showMessageDialog(gameClient.getContentPane(), "You are already connected!","Already Connected",JOptionPane.ERROR_MESSAGE);
			}

		} catch (NullPointerException ex) {
			System.out.println("NullPointerException happened here because of the Connection Error" +
			" as previously stated. Reason: Used a socket method without creating the socket");
		} catch (Exception ex) {
			ex.printStackTrace();
			JOptionPane.showMessageDialog(gameClient.getContentPane(), "Bizzare and Unknown Error","Error",JOptionPane.ERROR_MESSAGE);
		} 

	}

}
